package com.dkm.dkmproject.action;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dkm.dkmproject.domain.UserTb;
import com.dkm.dkmproject.domain.WalletTb;
import com.dkm.dkmproject.service.IUserTbService;
import com.dkm.dkmproject.service.IWalletTbService;
import com.dkm.dkmproject.utils.Message;

import com.dkm.dkmproject.utils.Wechatutils.WeixinSign;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 周佳佳
 * @since 2020-04-26
 */
@Controller
@ResponseBody
@RequestMapping("/userController")
@Api(description = "微信小程序用户接口文档")
public class UserTbController {
    Logger logger = (Logger) Logger.getLogger(String.valueOf(getClass()));
    @Autowired
    IUserTbService userTbService;
    @Autowired
    IWalletTbService walletTbService;

    @GetMapping("findById")
    public void wwt01() {
        UserTb userTb = new UserTb();
        userTb.setExp1("111");
        int rows = userTbService.insertSelective(userTb);
        if (rows > 0) {
            System.out.println("123");
        } else {
            System.out.println("333");
        }
        UserTb list = userTbService.selectById(1);
        System.out.printf("==" + list.getUserId());
    }

    @ApiOperation(value = "增加微信小程序用户的接口", notes = "如果用户存在返回1,用户不存在则增加返回2 失败返回3")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户主键，增加一条数据自动生成一个id"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userPhone", value = "用户手机号"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatName", value = "微信呢称", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatSex", value = "微信性别", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatProvinces", value = "微信省份 ", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatCountries", value = "微信国家", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wecahtWechatimg", value = "微信头像地址", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatWechatid", value = "微信唯一标识符 openId", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userAge", value = "年龄"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userName", value = "真实姓名"),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userState", value = "用户区分0为用户1为服务人员", required = true)
    })
    @GetMapping("addUser")
    public Map<String, Object> addUser(UserTb userTb) {
        Map<String, Object> map = new HashMap<>();
   /*     EntityWrapper<UserTb> queryWrapper = new EntityWrapper();
        queryWrapper.eq("wechat_wechatid", userTb.getWechatWechatid());
        logger.info( userTb.getWechatWechatid()+"===================");
        List<UserTb> list = userTbService.selectList(queryWrapper);*/

        UserTb userTbOne=userTbService.findById(userTb.getWechatWechatid());
        if (userTbOne!=null) {
            map.put("message", "用户已登录");
            map.put("state", "1");
            map.put("userId", userTbOne.getUserId());
            map.put("userState", userTbOne.getUserState());
            return map;
        } else {
            int rows = userTbService.insertOne(userTb);
            if (rows>0) {
                map.put("message", "用户增加成功");
                map.put("state", "2");
                map.put("userId", userTb.getUserId());
                map.put("userState", userTb.getUserState());
                WalletTb walletTb=new WalletTb();
                walletTb.setUserId(userTb.getUserId());
                walletTbService.insert(walletTb);
                return map;
            } else {
                map.put("state", "0");
                map.put("message", "用户增加失败");
                return map;
            }
        }
    }

    @ApiOperation(value = "修改微信小程序用户信息的接口", notes = "成功返回1 失败返回0")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户主键，增加一条数据自动生成一个id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userPhone", value = "用户手机号"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatName", value = "微信呢称"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatSex", value = "微信性别"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatProvinces", value = "微信省份 "),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatCountries", value = "微信国家"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wecahtWechatimg", value = "微信头像地址"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "wechatWechatid", value = "微信唯一标识符 openId"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userAge", value = "年龄"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userName", value = "真实姓名"),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userState", value = "用户区分0为用户1为服务人员")
    })
    @PostMapping("updateUser")
    public Message updateUser(@RequestBody UserTb userTb) {
        Message message = new Message();
        EntityWrapper<UserTb> queryWrapper = new EntityWrapper();
        queryWrapper.eq("user_phone", userTb.getUserPhone());
        queryWrapper.eq("exp3", userTb.getExp3());
        List<UserTb> list = userTbService.selectList(queryWrapper);
        if (!list.isEmpty()) {
            message.setNum(2);
            message.setMsg("该身份证或手机号码已被注册!");
            return message;
        }
        boolean flag = userTbService.insertOrUpdate(userTb);
        if (flag) {
            message.setNum(1);
            message.setMsg("修改成功");
            return message;
        } else {
            message.setNum(0);
            message.setMsg("修改失败");
            return message;
        }
    }

   /* *//**
     * 使用登录凭证
     *
     * @param code
     * @return
     *//*
    @ApiOperation(value = "传入code", notes = "返回openId")
    @GetMapping(value = "userInfo")
    public WeChatUtilBO login(String code) {
        try {
            return weChatUtil.codeToUserInfo(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/
    /**
     * 微信浏览器获取用户信息
     * @param code
     * @return
     */
    @GetMapping(value = "/login")
    public Map<String,Object> getUserInformation(String code, HttpServletRequest request) {
        Map<String,Object> map=new HashMap<>();
/*
        TbUser tbUser = new TbUser();
*/
        if (StringUtils.isEmpty(code)){
            map.put("失败","code为空");
            return map;
        }
        JSONObject jsonData = WeixinSign.getAccessToken(code);
        String openid = jsonData.getString("openid");
        String access_token = jsonData.getString("access_token");
        String refresh_token = jsonData.getString("refresh_token");
        HttpSession session = request.getSession();

        //验证access_token是否失效
        JSONObject validateData = WeixinSign.getValidateData(access_token, openid);
        if (!"0".equals(validateData.getString("errcode"))){
            //刷新access_token
            JSONObject refreshData= WeixinSign.getRefreshToken(refresh_token);
            access_token = refreshData.getString("access_token");
        }
        JSONObject userData = null;
        try {
            //拉取用户信息
            userData = WeixinSign.getUserInfo(access_token, openid);
            map.put("data",userData);
            map.put("openid",openid);
         /*   Object unionid = userData.get("unionid");
            Object nickName = userData.get("nickname");
            Object headimgurl = userData.get("headimgurl");
            Object sex = userData.get("sex");
            if (!StringUtils.isEmpty(unionid)) {
                //用户是否注册过
                tbUser = tbUserService.selectByUnionid(unionid.toString());
                if (StringUtils.isEmpty(tbUser)) {
                    tbUser = new TbUser();
                    String userId = UUID.randomUUID().toString().replace("-", "");
                    tbUser.setId(userId);
                    if (!StringUtils.isEmpty(nickName)){
                        tbUser.setNickname(nickName.toString());
                    }
                    if (!StringUtils.isEmpty(headimgurl)){
                        tbUser.setHeadimgUrl(headimgurl.toString());
                    }
                    if (!StringUtils.isEmpty(sex)){
                        tbUser.setSex(new Byte(sex.toString()));
                    }
                    tbUser.setCreateTime(new Date());
                    tbUser.setUnionid(unionid.toString());
                    tbUserService.insertUser(tbUser);
                }

            }*/
         return map;
        } catch (Exception e) {
            map.put("error","获取用户信息异常");
            return map;
        }
    /*    map.put("id",tbUser.getId());
        map.put("unionid",tbUser.getUnionid());
        map.put("headimgUrl",tbUser.getHeadimgUrl());
        map.put("nickname",tbUser.getNickname());
        map.put("sex",tbUser.getSex());
        map.put("province",userData.get("province").toString());
        map.put("city",userData.get("city").toString());
        map.put("openid",userData.get("openid").toString());
        map.put("sessionid",getSession().getId());*/
    }

    @ResponseBody
    @RequestMapping("findByUserAndName")
    public Message login(String userName,String userPwd, HttpServletRequest request){
        Message message=new Message();
        UserTb userTb=userTbService.selectUser(userName,userPwd);
        if(userTb!=null){
            message.setMsg("登陆成功");
            message.setNum(1);
            request.getSession().setAttribute("user",userTb);
        }else{
            message.setMsg("账户或密码失败");
            message.setNum(0);
        }

        return message;
    }
    /**
     * 查询是否已经登录
     * @param session
     * @return
     */
    @RequestMapping("/findModByManager")
    @ResponseBody
    public UserTb findModByManager(HttpSession session) {

        UserTb man = (UserTb) session.getAttribute("user");
        if(man==null){
            man = new UserTb();
            man.setUserId(0);
            man.setUserName("请重新登录");
        }
        return man;
    }

    /**
     * 退出系统清除session
     * @param session
     * @return
     */
    @RequestMapping("/removeSession")
    public String unLogin(HttpSession session) {
        session.invalidate();
        return "成功";
    }
}
